package com.xiaobaibai.security.common;

import com.alibaba.fastjson.JSONObject;
import com.xiaobaibai.common.TokenCommon;
import com.xiaobaibai.common.response.ResponseCode;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

public class TokenLogoutHandler implements LogoutHandler, LogoutSuccessHandler {

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response,
                       Authentication authentication) {

        if(authentication==null)
            return;
        //实际上是清除当时动态生成token的那个盐(在缓存中),但是呢我这里并没有存入缓存,所以我就将密匙换一下
        //去缓存中清除此userId对应的盐... 这里换成  变换密匙
        TokenCommon.TOKEN_ASSERT= UUID.randomUUID().toString();
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {

        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setStatus(200);
        PrintWriter writer = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", ResponseCode.SUCCESS.getCode());
        jsonObject.put("msg","登出");
        writer.write(jsonObject.toString());
    }
}
